﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Excel;
using System.IO;
using System.Windows.Forms;
namespace SCCM
{
    public static class EPPlusHelper
    {
        public static  void dataGridViewToExcel(DataGridView dgv)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出 Excel 文件到";
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel)//如果选择提醒导出
            {
                return;
            }
            Stream myStream;
            myStream = saveFileDialog.OpenFile();

            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string str = "";

            try
            {
                for (int i = 0; i < dgv.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += dgv.Columns[i].HeaderText;
                }
                sw.WriteLine(str);
                for (int j = 0; j < dgv.Rows.Count - 1; j++)
                {
                    StringBuilder tempStr =new StringBuilder();
                    for (int k = 0; k < dgv.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr.Append("\t");
                        }
                        tempStr.Append( dgv.Rows[j].Cells[k].Value.ToString());
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            finally
            {
                sw.Close();
                myStream.Close();
                MessageBox.Show("导出结束");
            }
        }
    }
}
